import { getFootballLiveList } from '@/server/news'
import { useRequest, useSafeState, useUpdateEffect } from 'ahooks'
import { useEffect, useRef, useState } from 'react'
import { getStartEndTime } from '@/common/tool'
import dayjs from 'dayjs'
import styles from './styles.module.scss'
import LiveIng from '@/assets/liveing.png'
import RenderJudge from '../RenderJudge'
import Link from 'next/link'
import { week } from '@/common/tool'
import { NavList } from '@/common/enum'
import { getBasketballLiveList } from '@/server/news'
import basketball_video from '@/assets/basketball_video.png'
import football_video from '@/assets/football_video.png'
import Image from '../Image'
import { useVirtualList } from 'ahooks';

const Live = ({ liveListData, match, ready, style, container, initFetch }) => {
  const useInitEffect = initFetch ? useEffect : useUpdateEffect //每次初始化都更新，只在数据更新时初始化
  console.log(liveListData)
  const [data, setData] = useState(() => {
    let state = []
    if (typeof liveListData?.today !== 'undefined') {
      state = state.concat([{ time: liveListData?.today?.time }, ...liveListData?.today?.data])
    }
    if (typeof liveListData?.yesterday !== 'undefined') {
      state = state.concat([{ time: liveListData?.yesterday?.time }, ...liveListData?.yesterday?.data])
    }
    return state
  })
  useEffect(() => {
    setData(() => {
      let state = []
      if (typeof liveListData?.today !== 'undefined') {
        state = state.concat([{ time: liveListData?.today?.time }, ...liveListData?.today?.data])
      }
      if (typeof liveListData?.yesterday !== 'undefined') {
        state = state.concat([{ time: liveListData?.yesterday?.time }, ...liveListData?.yesterday?.data])
      }
      console.log(state)
      return state
    })
  }, [liveListData])
  const api = {
    "0": getFootballLiveList,
    '1': getFootballLiveList,
    '2': getBasketballLiveList,
  }

  const containerRef = useRef(null);
  const wrapperRef = useRef(null);

  const { runAsync } = useRequest(Reflect.get(api, match.type), {
    onSuccess: (res, [params]) => {
      if (params?.count === 1) {
        //当前的
        setData([{ time: getStartEndTime().todayStartTime }, ...res])
      }
      if (params?.count === 2) {
        // 第二天的
        setData(s => [...s, { time: getStartEndTime().tomorrowEndTime }, ...res])
      }
    },
    manual: true,
    ready,
  })


  const [list, scrollTo] = useVirtualList(data, {
    containerTarget: containerRef,
    wrapperTarget: wrapperRef,
    itemHeight: (i, data) => data?.time ? 40 : 50,
    overscan: 5,
  });

  useInitEffect(() => {
    (async () => {
      const startParams = {
        pageNum: 1,
        pageSize: 3000,
        type: 1,
        date: getStartEndTime().todayStartTime
      }
      const endParams = {
        pageNum: 1,
        pageSize: 3000,
        type: 1,
        date: getStartEndTime().tomorrowEndTime
      }
      if (Number(match?.type === 0)) {
        if (!ready) return
        const [todayLiveData, yesterdayLiveData, todayLiveDataBasketball, yesterdayLiveDataBasketball] = await Promise.all([getFootballLiveList(startParams), getFootballLiveList(endParams), getBasketballLiveList(startParams), getBasketballLiveList(endParams)])
        //全部
        const currentDay = [...todayLiveData?.map(row => ({ ...row, matchType: 1 })), ...todayLiveDataBasketball?.map(row => ({ ...row, matchType: 2 }))] //今天的数据

        const yesterday = [...yesterdayLiveData?.map(row => ({ ...row, matchType: 1 })), ...yesterdayLiveDataBasketball?.map(row => ({ ...row, matchType: 2 }))] //明天
        const state = {
          today: {
            time: getStartEndTime().todayStartTime,
            data: currentDay
          },
          yesterday: {
            time: getStartEndTime().tomorrowEndTime,
            data: yesterday
          }
        }
        const cdate = [{ time: state?.today?.time }, ...state?.today?.data, { time: state?.yesterday?.time }, ...state?.yesterday?.data]
        setData(cdate)
        return
      }


      const params = {
        pageNum: 1,
        pageSize: 1000,
        type: 1,
        date: getStartEndTime()?.todayStartTime,
        count: 1,
      }
      if (match?.id) params.eventIds = match?.id
      await runAsync(params)
      params.date = getStartEndTime().tomorrowEndTime
      params.count = 2
      await runAsync(params)
    })()
  }, [match])
  const result = (row) => {
    if (!row?.matchType && row.status >= 2 && row.status <= 7) return true
    if (String(row?.matchType) === "1" && row.status >= 2 && row.status <= 7) return true
    if (String(row?.matchType) === "2" && row.status >= 2 && row.status <= 9) return true
    return false
  }
  const link = (row) => {
    const d = [NavList.a, ...NavList.f, ...NavList.b]
    const typer = row?.matchType || match?.type
    const { eventId } = row
    if (row?.liveUrlList?.length > 0) {
      const has = d.some(v => v.id === Number(eventId))
      if (has) return `/live/${typer}/${row?.id}/${eventId}`
      return `/live/${typer}/${row?.id}`
    }
    return "https://www.xinqiuzhibo.com/"
  }

  return (
    <section className={styles.live} style={style}>
      <section ref={containerRef} style={{ ...container, overflow: 'auto' }} className={styles.scrollBox}>
        <div ref={wrapperRef}>
          {
            list?.map(({ data: row }) => (
              <>
                <RenderJudge value={row?.id} active={
                  <div key={row?.id}>
                    <li >
                      <span className='textoverone'>{dayjs(row?.matchTime * 1000).format('HH:mm')}</span>
                      <span className='textoverone'>{row?.eventName}</span>
                      <div className={styles.matchInfo}>
                        <RenderJudge value={Number(row?.matchType || match?.type) === 1} active={
                          <>
                            <span className='textoverone'>{row?.homeTeamName}</span>
                            <Image src={row?.homeTeamLogo} type={row?.matchType || match?.type}></Image>
                            <i>VS</i>
                            <Image src={row?.awayTeamLogo} type={row?.matchType || match?.type}></Image>
                            <span className='textoverone'>{row?.awayTeamName}</span>
                          </>
                        } inactive={
                          <>
                            <span className='textoverone'>{row?.awayTeamName}</span>
                            <Image src={row?.awayTeamLogo} type={row?.matchType || match?.type}></Image>
                            <i>VS</i>
                            <Image src={row?.homeTeamLogo} type={row?.matchType || match?.type}></Image>
                            <span className='textoverone'>{row?.homeTeamName}</span>
                          </>
                        } />
                      </div>
                      <RenderJudge value={result(row)} active={
                        <span className={styles.liveStatus}>
                          <img src={LiveIng.src} loading="lazy" />
                          <span>直播中</span>
                        </span>
                      } />
                      <RenderJudge value={row?.status === 1} active={
                        <span className={styles.noStart}>
                          未开始
                        </span>
                      } />
                      <Link href={link(row)}>
                        <a className={styles.watch}> 观看直播 </a>
                      </Link>
                    </li>
                  </div>
                } />
                <RenderJudge value={row?.time} active={
                  <span className={styles.times}>
                    {dayjs(row?.time).format('M月D日') + week[dayjs(row?.time).format('d')]}
                  </span>
                } />
              </>
            ))
          }
        </div>
      </section>
    </section>
  )
}

Live.defaultProps = {
  ready: false,
  container: {
    height: '150vh',
  },
  wrapper: {},
  initFetch: false
}

// eslint-disable-next-line react/display-name
Live.Nav = ({ match, setMatch }) => {
  return (
    <section className={styles.navs}>
      <div>
        {
          [NavList.a, ...NavList.f, ...NavList.b]?.map((row, index) => (
            <span key={index} onClick={() => setMatch(row)} className={match?.id === row?.id ? styles.active : null}>
              {row?.name}
            </span>
          ))
        }
      </div>
    </section>
  )
}

// eslint-disable-next-line react/display-name
Live.Title = ({ type, text }) => {
  const img = {
    1: football_video,
    2: basketball_video
  }
  return (
    <div className={styles.titles}>
      <img src={img[type]?.src} alt="" />
      <span>{text}</span>
    </div>
  )
}


export default Live